package com.bluefish.bltuan.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {
	
	private static final String WINDOWS_FILE_SEPERATOR = "\\\\";
	
	private static final String ENCODE_FILE_SEPERATOR = "\\\\\\\\";
	
	private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);
	
	private static final String POINT = ".";
	
	private static final String BLANK = "";
	
	private static final String ATTACHMENT_FILENAME = "attachment; filename=";

    private static final String CONTENT_DISPOSITION = "Content-disposition";
    
    private static final int BUFFER_SIZE = 1024;

	public static enum FILEEXT{
		ZIP, JPEG, BMP, DOC
	};
	
	/**
	 * get the file EXT for type
	 * @param ext
	 * @return
	 */
	public String getExt(FILEEXT ext){
		switch (ext) {
		case ZIP:
			return ".zip";
		case JPEG:
			return ".jpg";
		case BMP:
			return ".bmp";
		case DOC:
			return ".doc";
		default:
			break;
		}
		return null;
	}
	
	/**
	 * get the file EXT from the filename,such as .jpg,.bmp,.zip.
	 * @param filename
	 * @return
	 */
	public static String getExt(String filename){
		int point = filename != null?filename.lastIndexOf(POINT):-1;
		return point > 0?filename.substring(point):BLANK;
	}
	
	/**
	 * get the pure file EXT from the filename,such as jpg,bmp,zip.
	 * @param filename
	 * @return
	 */
	public static String getPureExt(String filename){
		int point = filename != null?filename.lastIndexOf(POINT):-1;
		return point > 0?filename.substring(point + 1):BLANK;
	}
	
	public static File newFile(String filePath,String fileName){
		File folder = new File(filePath);
		if(!folder.exists()&&folder.mkdirs())
			LOG.info("create folder at " + filePath);
		return new File(folder+File.separator+fileName);
	}
	
	public static void delete(File file){
		if(file.exists()&&file.delete())
			LOG.info("delete image file "+file.getPath());
		else
			LOG.info("the file doesn't exist or can't be deleted!");
	}

	public static String encodePath(String path) {
		if(path != null && path.length() > 0){
			return path.replaceAll(WINDOWS_FILE_SEPERATOR, ENCODE_FILE_SEPERATOR);
		}
		return null;
	}

    public static void download(File file, String contentType) {
        String filepath = file.getAbsolutePath();
        String filename = file.getName();
        if(filepath!=null){
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(contentType);
            response.setContentLength((int) file.length());
            response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME+filename);
            writeToResponse(filepath, response);
        }
        LOG.info("Download file:" + filepath);
    }

    private static void writeToResponse(String filepath, HttpServletResponse response) {
    	BufferedInputStream inputStream = null;
        ServletOutputStream outputStream = null;
    	try {
            int size = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            inputStream = new BufferedInputStream(new FileInputStream(filepath));
            outputStream = ServletActionContext.getResponse().getOutputStream();
            while((size = inputStream.read(buffer, 0 , BUFFER_SIZE)) > 0){
                outputStream.write(buffer, 0, size);
            }
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            LOG.info(e.getMessage());
        } catch (IOException e) {
            LOG.info(e.getMessage());
        }finally{
            closeStream(outputStream, inputStream);
        }
    }

	private static void closeStream(ServletOutputStream outputStream,
			BufferedInputStream inputStream) {
		if(outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                LOG.info(e.getMessage());
            }
        }
        if(inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.info(e.getMessage());
            }
        }
	}
}
